package leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * Created by tiang on 2018/9/5.
 * Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest
 * transformation sequence from beginWord to endWord, such that:

 Only one letter can be changed at a time.
 Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
 Note:

 Return 0 if there is no such transformation sequence.
 All words have the same length.
 All words contain only lowercase alphabetic characters.
 You may assume no duplicates in the word list.
 You may assume beginWord and endWord are non-empty and are not the same.
 Example 1:

 Input:
 beginWord = "hit",
 endWord = "cog",
 wordList = ["hot","dot","dog","lot","log","cog"]

 Output: 5

 Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
 return its length 5.
 Example 2:

 Input:
 beginWord = "hit"
 endWord = "cog"
 wordList = ["hot","dot","dog","lot","log"]

 Output: 0

 Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
 */
public class WordLadder {
    /**
     * 一开始尝试用DFS做，但是结果一直不对，数据量太大的情况下会得到错误结果，目前尚未知道原因
     * @param beginWord 起始单词
     * @param endWord 目标单词
     * @param wordList 单词表
     * @return 转换步数
     */
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        if(!wordList.contains(endWord))
            return 0;
        boolean[] used = new boolean[wordList.size()];
        if(wordList.contains(beginWord))
            used[wordList.indexOf(beginWord)] = true;
        HashMap<String, Integer> map = new HashMap<>();
        int result = ladderLength(beginWord, endWord, wordList, used, map);
        return result;
    }

    private int ladderLength(String begin, String end, List<String> wordList, boolean[] used,
                             HashMap<String, Integer> inner) {
        if (begin.equals(end))
            return 1;
        if (inner.containsKey(begin))
            return inner.get(begin);
        List<Integer> sameWord = getSameWord(begin, wordList, used);
        if (sameWord.size() == 0)
            return 0;
        int result = 0;
        for (int i = 0; i < sameWord.size(); i++) {
            int index = sameWord.get(i);
            used[index] = true;
            int tempResult = ladderLength(wordList.get(index), end, wordList, used,inner);
            if (tempResult > 0) {
                if (result == 0 || tempResult < result) {
                    result = tempResult;
                }
            }
            used[index] = false;
        }
        result = result == 0 ? 0 : result + 1;
        inner.put(begin, result);
        return result;
    }

    /**
     * 查找与目标单词相差一个字母的单词下标
     * @param word 目标单词
     * @param wordList 单词表
     * @param used 是否已经使用过
     * @return 返回下标列表
     */
    public List<Integer> getSameWord(String word, List<String> wordList, boolean[] used){
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<wordList.size();i++){
            if(used[i])
                continue;
            int c = 0;
            for(int j=0;j<word.length();j++){
                if(word.charAt(j) != wordList.get(i).charAt(j))
                    c++;
            }
            if(c == 1){
                list.add(i);
            }
        }
        return list;
    }

    /**
     * 采用BFS重新做，这下AC了，也不知道为什么DFS一直AC不了
     * @param beginWord 起始单词
     * @param endWord 目标单词
     * @param wordList 单词表
     * @return 转换步数
     */
    public int ladderLengthBFS(String beginWord, String endWord, List<String> wordList) {
        if(!wordList.contains(endWord))
            return 0;
        // 记录单词是否使用过
        boolean[] used = new boolean[wordList.size()];
        // 存储每一步的单词
        HashSet<String> now = new HashSet<>();
        now.add(beginWord);
        // 如果单词表中存在起始单词，那么起始单词视为已经使用过
        if(wordList.contains(beginWord))
            used[wordList.indexOf(beginWord)] = true;
        // 记录转换次数
        int count = 1;
        while(!now.isEmpty()){
            HashSet<String > next = new HashSet<>();
            // 寻找经过一次转换能得到的所有单词列表
            for(String str : now){
                List<Integer> list = getSameWord(str, wordList, used);
                for(int i=0;i<list.size();i++){
                    next.add(wordList.get(list.get(i)));
                    used[list.get(i)] = true;
                }
            }
            now = next;
            count++;
            // 已经达到目标单词，就返回
            if(now.contains(endWord))
                return count;
        }
        // 如果搜寻完毕仍无法达到，就返回0
        return 0;
    }


}
